package com.demo.ping.service.impl;

import com.demo.ping.service.PingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
/**
 *  @author Jofo
 */
@Slf4j
@Service
public class PingServiceImpl implements PingService {

    private final WebClient webClient;

    /**
     * The constructor receives the WebClient.Builder instance and a string type Pong server URL,
     * Build a WebClient instance based on these parameters for subsequent network requests
     *
     * @param webClientBuilder WebClient builder for building WebClient instances
     * @param webPongUrl The URL address of the Pong server obtained from the configuration file
     */
    public PingServiceImpl(WebClient.Builder webClientBuilder, @Value("${pongServer.url}") String webPongUrl) {
        this.webClient = webClientBuilder.baseUrl(webPongUrl).build();
    }


    /**
     * Send a "hello" message and receive a response
     * If the request is successful, the response body will be returned, and if an exception occurs, a Mono object containing the exception will be returned
     *
     * @param traceId trace ID for tracing requests
     * @return Returns a Mono object containing a string response or exception received from the server
     */
    @Override
    public Mono<String> sayHello(String traceId) {
        try {
            // use WebClient to send a GET request, obtain the response body, and convert it <String>to Mono
            return webClient.get().uri("/pong?msg=hello&traceId=" + traceId).retrieve().bodyToMono(String.class);
        } catch (Exception e) {
            // catch the exception and return a Mono object containing the exception
            return Mono.error(e);
        }
    }
}
